package pri.hillchen.std.netty.timeserver.unpack;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.Date;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 16:55 2018/3/30 0030.
 */
public class DecodeTimeServerHandler extends ChannelHandlerAdapter {
    public static final String QUERY_TIME_COMMAND = "CURRENT_TIME";
    public static final String LINE_SEPARATOR = System.getProperty("line.separator");
    private int counter = 0;
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String  order = (String) msg;
        System.out.println(String.format("time server receive order:%s,receive order counter:%s",order,++counter));
        String currentTime = QUERY_TIME_COMMAND.equals(order) ?
                new Date(System.currentTimeMillis()).toString() : "bad order";
        ByteBuf resp = Unpooled.copiedBuffer((currentTime + LINE_SEPARATOR).getBytes());
        ctx.writeAndFlush(resp);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
